import React, { useState, useEffect, useRef, useMemo } from 'react';
import { useDrop, useDrag } from 'react-dnd';
import { HolderOutlined } from '@ant-design/icons';
import './index.less';

// 行组件
function RowItem({ rowData, index, depth, moveRow, addRow }: { rowData: any, depth: number, index: number, moveRow: (dragIndex: number, hoverIndex: number) => void, addRow: (index: number, data: any) => void }) {

    const ref = useRef<HTMLSpanElement | null>(null);

    // collectedProps
    const [{ isDragging }, drag, preview] = useDrag({
        type: 'ROW',
        item: { index, type: 'ROW' },
        collect: (monitor) => {
            return {
                isDragging: monitor.isDragging(),
            }
        },
    });

    const [{ isOver, dropPosition, leftOffset }, drop] = useDrop({
        accept: ['ROW', 'COMMAND'],
        collect: (monitor) => {
            console.log(monitor.getClientOffset(), 'useDrop monitor')
            if (!ref.current) {
                return {
                    isOver: false,
                    dropPosition: null,
                    leftOffset: 0
                };
            }

            const clientOffset = monitor.getClientOffset();
            if (!clientOffset) {
                return {
                    isOver: false,
                    dropPosition: null,
                    leftOffset: 0
                };
            }

            const rect = ref.current.getBoundingClientRect();
            const hoverMiddleY = (rect.bottom - rect.top) / 2;
            const hoverClientY = clientOffset.y - rect.top;

            return {
                isOver: monitor.isOver(),
                dropPosition: hoverClientY < hoverMiddleY ? 'top' : 'bottom',
                leftOffset: clientOffset.x - rect.left
            };
        },
        drop: (item: { index: number, type: string, command: any }) => {
            if (item.type === 'COMMAND') {
                // 新增
                const hoverIndex = dropPosition === 'top' ? index : index + 1;
                addRow(hoverIndex, {
                    key: Date.now().toString(),
                    cmd: item.command.name,
                    target: 'Target',
                    value: 'Value',
                    ops: 'Ops'
                });
            } else if (item.type === 'ROW') {
                // 移动
                const dragIndex = item.index;
                const hoverIndex = dropPosition === 'bottom' ? index : index - 1;
                if (dragIndex === hoverIndex) {
                    return;
                }
                moveRow(dragIndex, hoverIndex);
                item.index = hoverIndex;
            }
        }
    });

    return (
        <div
            ref={(node) => {
                preview(node);
                drop(node);
            }}
            className={`row-item ${leftOffset} ${isDragging ? 'dragging' : ''} ${isOver ? `drop-${dropPosition}` : ''}`}
        >
            <div ref={(node) => {
                ref.current = node;
                drag(drop(ref));
            }} style={{
                cursor: 'move',
                marginRight: '5px'
            }}>
                {/* @ts-ignore */}
                <HolderOutlined />
            </div>
            <div className="row-col index-col" >
                {index + 1}
            </div>
            <div className="row-col cmd-col" >{rowData.cmd}</div>
            <div className="row-col target-col"  >{rowData.target}</div>
            <div className="row-col value-col"  >{rowData.value}</div>
            <div className="row-col ops-col"  >{rowData.ops}</div>
        </div>
    )
}

// 表格组件
export default function ListView() {

    const [dataSource, setDataSource] = useState<any[]>([]);

    // 移动行
    const moveRow = (dragIndex: number, hoverIndex: number) => {
        const newData = [...dataSource];
        const [removed] = newData.splice(dragIndex, 1);
        newData.splice(hoverIndex, 0, removed);
        setDataSource(newData);
    };

    // 新增行
    const addRow = (index: number, data: any) => {
        const newData = [...dataSource];
        newData.splice(index, 0, {
            ...data,
            key: Date.now().toString(),
        });
        setDataSource(newData);
    };

    // 模拟数据
    useEffect(() => {
        const commands = [
            {
                "id": "5cb6f743-5c96-4ac4-bcef-f8479fbd1890",
                "cmd": "store",
                "target": "fast",
                "value": "!replayspeed",
                "description": "",

            },
            {
                "id": "5cb6f743-5c96-4ac4-bcef-f8479fbd1891",
                "cmd": "open",
                "target": "https://ui.vision/demo/executeScript",
                "value": "",
                "description": "",

            },
            {
                "id": "5cb6f743-5c96-4ac4-bcef-f8479fbd1892",
                "cmd": "echo",
                "target": "How to use gotoIf and label(s) for flow control. For a while demo, see the DemoSaveCSV macro.",
                "value": "",
                "description": "",

            },
            {
                "id": "5cb6f743-5c96-4ac4-bcef-f8479fbd1893",
                "cmd": "executeScript",
                "target": "return (new Date().getHours())",
                "value": "mytime",
                "description": "",

            },
            {
                "id": "5cb6f743-5c96-4ac4-bcef-f8479fbd1894",
                "cmd": "echo",
                "target": "mytime = ${mytime}",
                "value": "",
                "description": "",

            },
            {
                "id": "5cb6f743-5c96-4ac4-bcef-f8479fbd1895",
                "cmd": "if",
                "target": "${mytime}  > 16",
                "value": "",
                "description": "",

                "children": [
                    {
                        "id": "5cb6f743-5c96-4ac4-bcef-f8479fbd1896",
                        "cmd": "echo",
                        "target": "下午好！",
                        "value": "",
                        "description": ""
                    },
                    {
                        "id": "5cb6f743-5c96-4ac4-bcef-f8479fbd1897",
                        "cmd": "echo",
                        "target": "下午好！",
                        "value": "",
                        "description": ""
                    },
                    {
                        "id": "5cb6f743-5c96-4ac4-bcef-f8479fbd1898",
                        "cmd": "echo",
                        "target": "下午好！",
                        "value": "",
                        "description": ""
                    },
                    {
                        "id": "5cb6f743-5c96-4ac4-bcef-f8479fbd1899",
                        "cmd": "echo",
                        "target": "下午好！",
                        "value": "",
                        "description": ""
                    },
                ]
            },
            {
                "id": "97dcffc9-b1e8-4ece-95e9-ac9d658c5222",
                "cmd": "else",
                "target": "",
                "value": "",
                "description": "",

                "children": [
                    {
                        "id": "97dcffc9-b1e8-4ece-95e9-ac9d658c5223",
                        "cmd": "echo",
                        "target": "上午好",
                        "value": "",
                        "description": ""
                    },
                    {
                        "id": "97dcffc9-b1e8-4ece-95e9-ac9d658c5224",
                        "cmd": "echo",
                        "target": "上午好",
                        "value": "",
                        "description": ""
                    },
                    {
                        "id": "97dcffc9-b1e8-4ece-95e9-ac9d658c5225",
                        "cmd": "echo",
                        "target": "上午好",
                        "value": "",
                        "description": ""
                    },
                    {
                        "id": "97dcffc9-b1e8-4ece-95e9-ac9d658c5226",
                        "cmd": "echo",
                        "target": "上午好",
                        "value": "",
                        "description": ""
                    },
                ]

            },
            {
                "id": "97dcffc9-b1e8-4ece-95e9-ac9d658c5227",
                "cmd": "storeAttribute",
                "target": "//input[@id='sometext-WRONG-ID-TEST']@size",
                "value": "boxsize",
                "description": "",

            },
            {
                "id": "97dcffc9-b1e8-4ece-95e9-ac9d658c5228",
                "cmd": "if",
                "target": "${boxsize} == \"#LNF\"",
                "value": "",
                "description": "",

            },
            {
                "id": "97dcffc9-b1e8-4ece-95e9-ac9d658c5229",
                "cmd": "echo",
                "target": "The xpath was not found. In this case the variable gets filled with #LNF (Locator Not Found).",
                "value": "blue",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe1",
                "cmd": "storeAttribute",
                "target": "//input[@id='sometext']@size",
                "value": "boxsize",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe2",
                "cmd": "echo",
                "target": "With correct Xpath ID we get: Boxsize = ${boxsize}",
                "value": "green",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe3",
                "cmd": "end",
                "target": "",
                "value": "",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe4",
                "cmd": "gotoIf",
                "target": "${boxsize} > 70",
                "value": "BOX-TOO-BIG",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe5",
                "cmd": "type",
                "target": "id=sometext",
                "value": "This box is ${boxsize} chars wide",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe6",
                "cmd": "executeScript",
                "target": "document.title = ${boxsize};",
                "value": "",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe7",
                "cmd": "gotoLabel",
                "target": "END",
                "value": "",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe8",
                "cmd": "label",
                "target": "BOX-TOO-BIG",
                "value": "",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe9",
                "cmd": "echo",
                "target": "Input box too big. This is just a test of gotoIf",
                "value": "",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe10",
                "cmd": "executeScript",
                "target": "document.title = \"Just a gotoIf test. This line should not be reached unless you edit the macro\"",
                "value": "",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe11",
                "cmd": "label",
                "target": "END",
                "value": "",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe12",
                "cmd": "echo",
                "target": "test case completed",
                "value": "",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe13",
                "cmd": "comment",
                "target": "",
                "value": "",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe14",
                "cmd": "onError",
                "target": "#goto",
                "value": "fixerror",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe15",
                "cmd": "type",
                "target": "id=sometext",
                "value": "this line works",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe16",
                "cmd": "type",
                "target": "id=sometextXXXXX",
                "value": "this line has the wrong ID...",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe17",
                "cmd": "echo",
                "target": "this line is never reached, because of the error above",
                "value": "blue",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe18",
                "cmd": "gotoLabel",
                "target": "end-part2",
                "value": "",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe19",
                "cmd": "label",
                "target": "fixerror",
                "value": "",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe20",
                "cmd": "echo",
                "target": "here we can have code that handles the error..",
                "value": "green",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe21",
                "cmd": "type",
                "target": "id=sometext",
                "value": "Fix Error Section: This command works.",
                "description": "",

            },
            {
                "id": "1fa012a7-cf66-4e89-988d-67510488cfe22",
                "cmd": "label",
                "target": "end-part2",
                "value": "",
                "description": "",

            }
        ]
        setDataSource(commands)
    }, []);


    return (
        <div className="list-view" >
            <div className="command-list-wrapper"  >
                {
                    dataSource.map((item, index) => {
                        return <RowItem
                            index={index}
                            rowData={item}
                            key={item.id}
                            depth={1}
                            moveRow={moveRow}
                            addRow={addRow}
                        />
                    })
                }
            </div>
        </div>
    );
};